<template>
  <div class="maincontainer">
    <div class="components-container">
      <split-pane split="vertical" :default-percent="30" @resize="resize">
        <template slot="paneL">
          <div class="left-container">
            <el-tabs v-model="activeName" type="border-card" stretch>
              <el-tab-pane label="患者列表" name="first">
                <!-- 添加搜索栏和叫号按钮 -->
                <div style="margin-bottom: 10px;">
                  <el-input
                    v-model="searchQuery"
                    placeholder="请输入姓名或ID搜索"
                    style="width: 200px; margin-right: 10px;"
                  />
                </div>
                <el-table
                  v-loading="loading"
                  :data="filteredPatients"
                  stripe
                  height="550"
                  element-loading-text="正在加载..."
                  element-loading-spinner="el-icon-loading"
                  element-loading-background="rgba(0, 0, 0, 0.8)"
                  style="width: 100%"
                >
                  <el-table-column label="ID" prop="patient_id" width="50px" />
                  <el-table-column label="姓名" prop="patient_name" width="75px" />
                  <el-table-column label="年龄" prop="patient_age" width="50px" />
                  <el-table-column label="性别" prop="patient_gender" width="50px" />
                  <el-table-column align="center" fixed="right" label="操作">
                    <template slot-scope="scope">
                      <el-tooltip v-if="scope.$index === 0" class="item" effect="dark" content="选择此病人处理病历" placement="right">
                        <el-button type="primary" size="mini" @click="callPatient(scope.row)">叫号</el-button>
                      </el-tooltip>

                    </template>
                  </el-table-column>
                </el-table>

              </el-tab-pane>
              <!-- 当前患者与病历列表 -->
              <el-tab-pane label="当前患者" name="second">

                <el-descriptions size="mini" title="患者基本信息" direction="vertical" :column="3" border>
                  <el-descriptions-item :span="2"><template slot="label">
                    <i class="el-icon-user" />
                    姓名
                  </template>{{ curpatient.patient_name }}</el-descriptions-item>
                  <el-descriptions-item label="ID" :span="2">{{ curpatient.patient_id }}</el-descriptions-item>
                  <el-descriptions-item :span="2"><template slot="label">
                    <i class="el-icon-mobile-phone" />
                    手机号
                  </template>{{ curpatient.patientPhone }}</el-descriptions-item>
                  <el-descriptions-item label="年龄" :span="2">{{ curpatient.patient_age }}</el-descriptions-item>
                  <el-descriptions-item label="新建病历" :span="2">
                    <el-button size="mini" type="success" icon="el-icon-plus" @click="createnewrecord" />
                  </el-descriptions-item>
                  <el-descriptions-item v-if="isChoose2" label="诊毕" :span="2">
                    <el-popover v-model="visible" placement="top" width="160" trigger="click">
                      <p>确定诊毕吗？</p>
                      <div style="text-align: right; margin: 0">
                        <el-button size="mini" type="text" @click="visible = false">取消</el-button>
                        <el-button type="primary" size="mini" @click="RecordOver()">确定</el-button>
                      </div>
                      <el-button slot="reference" size="mini" type="danger" icon="el-icon-delete" />
                    </el-popover>

                  </el-descriptions-item>
                </el-descriptions>

                <el-divider content-position="center">患者病历列表</el-divider>

                <el-table
                  :data="curpatientMedicalRecordList"
                  height="500"
                  style="width: 100%"
                  :default-sort="{ prop: 'date', order: 'descending' }"
                >
                  <el-table-column prop="date" label="日期" />
                  <el-table-column prop="title" label="标题" />

                  <el-table-column label="病历状态" class-name="status-col">
                    <template slot-scope="{row}">
                      <el-tag :type="row.is_completed | statusFilter">
                        {{ row.is_completed === false ? '未完成' : '已完成' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center">
                    <template slot-scope="{row}">
                      <el-button v-if="row.is_completed === false" size="mini" type="success" @click="handleEdit(row)">
                        编辑
                      </el-button>
                      <el-button v-if="row.is_completed === true" size="mini" @click="handleSee(row)">
                        查看
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </div>
        </template>

        <!-- 病历编辑区 -->
        <template slot="paneR">
          <!-- 选了病人和病历 -->
          <div v-if="isChoose" class="createPost-container">
            <!-- 病历编辑 -->
            <el-empty v-if="isRecordOver === 0" description="暂未选择病历" />
            <div v-else-if="isRecordOver === 1">
              <el-form ref="postForm" :model="postForm" :rules="rules">

                <div class="createPost-main-container">
                  <el-row>
                    <!-- 警告 -->
                    <el-alert title="编辑功能一旦病人就诊完成即不可用" type="warning" description="如有问题请咨询管理员" show-icon />
                    <!-- 标题 -->
                    <el-form-item prop="medical_record_title">
                      <MDinput v-model="postForm.medical_record_title" :maxlength="100" name="name" required>
                        Title
                      </MDinput>
                    </el-form-item>
                  </el-row>
                  <el-button type="success" @click="submitForm">
                    保存
                  </el-button>
                  <!-- 内容 -->
                  <el-form-item prop="medical_record_content" style="margin-bottom: 30px;">
                    <Tinymce ref="tinymce" v-model="postForm.medical_record_content" :height="400" />
                  </el-form-item>
                </div>
              </el-form>
            </div>
            <!-- 病历查看 -->
            <div v-else>
              <el-card shadow="never">
                <p style="text-align: center; border: 3px solid black; padding: 10px;">{{ watchForm.medical_record_title
                }}</p>
                <el-divider />
                <div v-html="watchForm.medical_record_content" />
              </el-card>
            </div>
          </div>

          <!-- 没有选病人和病历 -->
          <div v-else class="nopatient">
            <el-row>
              <el-col :span="12">
                <h1 class="text-jumbo text-ginormous">
                  Oops!
                </h1>
                <h2>请先叫号一个当前患者并选择可以编辑的病历</h2>
              </el-col>
              <el-col :span="12">
                <img :src="errGif" width="313" height="428" alt="Girl has dropped her ice cream.">
              </el-col>
            </el-row>
          </div>

        </template>
      </split-pane>
    </div>
    <div style="height: 100px;">
      常用模板
      <el-select v-model="valueTemplate" placeholder="请选择模板" @change="change">
        <el-option-group v-for="group in options" :key="group.label" :label="group.label">
          <el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="item.value" />
        </el-option-group>
      </el-select>
    </div>
  </div>
</template>

<script>
import splitPane from 'vue-splitpane'
import Tinymce from '@/components/Tinymce'
import errGif from '@/assets/401_images/401.gif'
import MDinput from '@/components/MDinput'
import recordTemplates from '@/assets/recordTemplate'
import { DocterCallNumber, DocterCreateNewRecord, DocterEndRecord, DocterGetPaientList, DocterGetPaientRecordList, DocterGetRecord, DocterUpdateRecord } from '@/api/medicalEdit'

// const defaultForm = {
//   medical_record_title: '', // 文章题目
//   medical_record_content: '', // 文章内容
//   medical_record_id: 2
// }

export default {
  name: 'MedicalEdit',
  components: { MDinput, splitPane, Tinymce },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    return {
      presentUser: {},
      loading: false,
      visible: false,
      isChoose2: false,
      // postForm: Object.assign({}, defaultForm),
      postForm: {
        medical_record_title: '', // 文章题目
        medical_record_content: '', // 文章内容
        medical_record_id: 2,
        medical_record_patient_id: 1,
        medical_record_date: '2025-01-03',
        medical_record_is_completed: false
      },
      watchForm: {
        medical_record_title: '', // 文章题目
        medical_record_content: '', // 文章内容
        medical_record_id: 2,
        medical_record_date: '2025-01-03',
        medical_record_patient_id: 1,
        medical_record_is_completed: false
      },
      rules: {
        medical_record_title: [{ validator: validateRequire }]
      },
      isChoose: false,
      isRecordOver: 0,
      errGif: errGif + '?' + +new Date(),
      activeName: 'first',
      // 分页
      tableData: [], // 所有的数据
      pageNum: 1, // 当前的页码
      pageSize: 10, // 每页显示的个数
      total: 0,

      recordTemplates,
      options: [{
        label: '门诊病历',
        options: [{
          value: 1,
          label: '初诊门诊病历'
        }, {
          value: 2,
          label: '复诊门诊病历'
        }]
      }, {
        label: '住院病历',
        options: [{
          value: 3,
          label: '住院病历'
        }]
      }, {
        label: '手术病历',
        options: [{
          value: 4,
          label: '手术病历'
        }]
      }],
      valueTemplate: '',

      // 患者相关
      patient: [
        {
          patient_id: 1,
          patient_name: '小mi',
          patient_age: '22',
          patient_gender: '男',
          patientPhone: '13340287626',
          patientAddress: '重庆市渝北区',
          patientstatus: 1
        },
        {
          patient_id: 2,
          patient_name: '小红和',
          patient_age: '25',
          patient_gender: '女',
          patientPhone: '13840287626',
          patientAddress: '重庆市南岸区',
          patientstatus: 1
        },
        {
          patient_id: 3,
          patient_name: '小刚',
          patient_age: '30',
          patient_gender: '男',
          patientPhone: '13940287626',
          patientAddress: '重庆市沙坪坝区',
          patientstatus: 2
        },
        {
          patient_id: 6,
          patient_name: '小刚',
          patient_age: '30',
          patient_gender: '男',
          patientPhone: '13940287626',
          patientAddress: '重庆市沙坪坝区',
          patientstatus: 2
        },
        {
          patient_id: 4,
          patient_name: '小刚',
          patient_age: '30',
          patient_gender: '男',
          patientPhone: '13940287626',
          patientAddress: '重庆市沙坪坝区',
          patientstatus: 1
        },
        {
          patient_id: 9,
          patient_name: '小刚',
          patient_age: '30',
          patient_gender: '男',
          patientPhone: '13940287626',
          patientAddress: '重庆市沙坪坝区',
          patientstatus: 2
        },
        {
          patient_id: 3,
          patient_name: '小刚',
          patient_age: '30',
          patient_gender: '男',
          patientPhone: '13940287626',
          patientAddress: '重庆市沙坪坝区',
          patientstatus: 1
        },
        {
          patient_id: 8,
          patient_name: '小刚',
          patient_age: '30',
          patient_gender: '男',
          patientPhone: '13940287626',
          patientAddress: '重庆市沙坪坝区',
          patientstatus: 2
        }
      ],
      // 当前患者
      curpatient: {
        patient_id: null,
        patient_name: '\\',
        patient_age: '\\',
        patient_gender: '\\',
        patientPhone: '\\',
        patientAddress: '\\',
        patientstatus: null

      },
      curpatientMedicalRecord: [
        // {

        //   medical_record_id: 1,
        //   medical_record_title: '标题1',
        //   medical_record_content: "<p>常见病历模板1</p><table style='width: 50%; border-collapse: collapse;' border='1'><tbody><tr><td style='width: 50%;'>诊断结果</td><td style='width: 50%;'>感冒</td></tr><tr><td style='width: 50%;'>主要描述</td><td style='width: 50%;'>发烧</td></tr></tbody></table>",
        //   medical_record_is_completed: 1
        // },
        // {
        //   medical_record_id: 2,
        //   medical_record_title: '232',
        //   medical_record_content: "<p>常见病历模板2</p><table style='width: 50%; border-collapse: collapse;' border='1'><tbody><tr><td style='width: 50%;'>诊断结果</td><td style='width: 50%;'>感冒</td></tr><tr><td style='width: 50%;'>主要描述</td><td style='width: 50%;'>发烧</td></tr></tbody></table>",
        //   medical_record_is_completed: 1
        // },
        // {
        //   medical_record_id: 3,
        //   medical_record_title: 'adada',
        //   medical_record_content: "<p>常见病历模板3</p><table style='width: 50%; border-collapse: collapse;' border='1'><tbody><tr><td style='width: 50%;'>诊断结果</td><td style='width: 50%;'>感冒</td></tr><tr><td style='width: 50%;'>主要描述</td><td style='width: 50%;'>发烧</td></tr></tbody></table>",
        //   medical_record_is_completed: 2
        // },
        // {
        //   medical_record_id: 5,
        //   medical_record_title: '佛山市',
        //   medical_record_content: "<p>常见病历模板4</p><table style='width: 50%; border-collapse: collapse;' border='1'><tbody><tr><td style='width: 50%;'>诊断结果</td><td style='width: 50%;'>感冒</td></tr><tr><td style='width: 50%;'>主要描述</td><td style='width: 50%;'>发烧</td></tr></tbody></table>",
        //   medical_record_is_completed: 2
        // }
      ],
      curpatientMedicalRecordList: [],
      // 添加搜索查询字段
      searchQuery: '',
      searchQuery222: ''

    }
  },
  computed: {
  // 添加计算属性用于过滤患者
    filteredPatients() {
      const query = this.searchQuery || '' // 确保 searchQuery 不为 undefined 或 null
      return this.patient.filter(data => {
        if (!data) return false // 防止 data 为 null 或 undefined
        return (data.patient_name && data.patient_name.includes(query)) ||
             (data.patient_id && data.patient_id.toString().includes(query))
      })
    }
  },
  watch: {
    activeName(newVal, oldVal) {
      if (oldVal) {
        // 移除旧标签页中所有元素的焦点
        const oldTabPane = document.querySelector(`#pane-${oldVal}`)
        if (oldTabPane) {
          const focusableElements = oldTabPane.querySelectorAll('*')
          focusableElements.forEach(el => el.blur())
        }
      }

      // 确保焦点移动到新标签页的第一个可聚焦元素
      this.$nextTick(() => {
        const newTabPane = document.querySelector(`#pane-${newVal}`)
        if (newTabPane) {
          const focusableElements = newTabPane.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')
          if (focusableElements.length > 0) {
            focusableElements[0].focus()
          }
        }
      })
    }
  },
  mounted() {
    this.presentUser = JSON.parse(localStorage.getItem('User'))
    console.log('初始化医生：', this.presentUser)
    // TODO:用doctorid去获取患者列表
    this.initPatient()
  },
  methods: {
    resize() {
      // console.log('resize')
    },
    // 获取病人列表
    async initPatient() {
      this.loading = true
      const data = { doctor_id: this.presentUser.doctor_id }
      // console.log('data3', data)
      const res = await DocterGetPaientList(data)
      this.patient = res
      this.loading = false
      // console.log('patient', this.patient)
    },
    // 添加叫号方法
    callPatient(row) {
      this.curpatient = row
      console.log('当前患者', row)
      localStorage.setItem('patient', JSON.stringify(row))
      // 用patient_id去获取病历列表
      this.initAllrecord(row.patient_id)
      this.reallyCall(row.patient_id)
      this.initPatient()
      this.activeName = 'second'
      this.isChoose = true
    },
    async reallyCall(number) {
      const data = { doctor_id: this.presentUser.doctor_id }
      const res = await DocterCallNumber(data)
      console.log('res', res)
    },
    async initAllrecord(number) {
      const data = {
        patient_id: number
      }
      const res = await DocterGetPaientRecordList(data)
      this.curpatientMedicalRecordList = res.medical_records
      // console.log('mmmmmmmmm', this.curpatientMedicalRecordList)
    },
    async createnewrecord() {
      try {
        const data1 = this.curpatient.appointment_id
        console.log('data1', data1)
        const data = {
          appointment_id: data1
        }
        await DocterCreateNewRecord(data)
        this.initAllrecord(this.curpatient.patient_id)
        // 成功提示
        this.$message({
          message: '记录创建成功',
          type: 'success'
        })
      } catch (error) {
        console.error('创建记录失败:', error)
        // 错误提示
        this.$message.error('创建记录失败，请稍后再试')
      }
    },
    async submitForm() {
      console.log('提交修改')
      console.log(this.postForm)
      const data = {
        medical_record_id: this.postForm.medical_record_id,
        medical_record_content: this.postForm.medical_record_content,
        medical_record_is_completed: false,
        medical_record_title: this.postForm.medical_record_title
      }
      console.log('data', data)
      try {
        const response = await DocterUpdateRecord(data)
        console.log('更新病历成功:', response)
        this.initAllrecord(this.curpatient.patient_id)
        // 处理成功后的逻辑，例如刷新列表等
      } catch (error) {
        console.error('更新病历失败:', error.response ? error.response.data : error.message)
        // 显示用户友好的错误提示
        this.$message({
          message: '更新病历失败，请稍后再试',
          type: 'error'
        })
      }
    },
    async handleEdit(row) {
      this.isChoose2 = true
      console.log('编辑')
      // console.log(row)
      const number = row.id
      const res = await DocterGetRecord({ medical_record_id: number })
      this.postForm = res
      this.isRecordOver = 1
    },
    async handleSee(row) {
      this.isChoose2 = false
      console.log('查看')
      // this.getRecordDetail(row.id)
      const number = row.id
      const res = await DocterGetRecord({ medical_record_id: number })
      this.watchForm = res
      // console.log(row)
      // console.log('--------------------------------')
      // console.log(this.watchForm)
      this.isRecordOver = 2
    },
    async RecordOver() {
      this.visible = false
      // 修改病历状态
      const data = {
        medical_record_id: this.postForm.medical_record_id,
        medical_record_is_completed: true
      }
      await DocterEndRecord(data)
      this.initAllrecord(this.curpatient.patient_id)
    },
    change(val) {
      console.log(val)
      const templateContent = this.getTemplateContent(val)
      this.postForm.medical_record_content = templateContent
      this.$nextTick(() => {
        if (this.$refs.tinymce) {
          this.$refs.tinymce.setContent(templateContent)
        }
      })
    },
    getTemplateContent(val) {
      switch (val) {
        case 1:
          return this.recordTemplates.firstCheck
        case 2:
          return this.recordTemplates.nextCheck
        case 3:
          return this.recordTemplates.zhuyuan
        case 4:
          return this.recordTemplates.shoushu
        default:
          return ''
      }
    }
  }
}
</script>

<style scoped>
.createPost-container {
  position: relative;
  /* background-color: #3898FF; */

}

.createPost-main-container {
  padding: 5px 5px 5px 5px;
  /* background-color: #95E1D3; */
}

.nopatient {
  max-width: 100%;
  background-color: #ffffff;
  margin: auto;
  display: flex;
  justify-content: space-around;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.patient-name {
  color: #3898FF;
  font-size: 18px;
  /* 根据需要调整字体大小 */
}

.maincontainer {
  padding: 15px;
  background-color: rgb(240, 242, 245);
  position: relative;
}

.components-container {
  position: relative;
  height: 115vh;
  margin: auto;
}

.left-container {
  /* background-color: #F38181; */
  height: 100%;
}

.right-container {
  background-color: #FCE38A;
  height: 100%;
}

.top-container {
  background-color: #FCE38A;
  width: 100%;
  height: 100%;
}

.bottom-container {
  width: 100%;
  background-color: #95E1D3;
  height: 100%;
}
</style>
